package kv

import (
	"data/config"
	"data/view/auth"
	"data/view/auth/auth_const"
	"data/view/common"
	"data/view/user"
	"fmt"
	"public/message"
	"public/mysqldb"
	"public/tools"
	"strings"

	"github.com/ant0ine/go-json-rest/rest"
)

//获取全部数据字典
func GetAll(w rest.ResponseWriter, r *rest.Request) {
	var req GetAllParam
	tools.GetRequestJsonObj(r, &req)

	//参数检测
	if !tools.CheckParam(req.Access_token) {
		w.WriteJson(message.GetErrorMsg(message.ParameterInvalid, req))
		return
	}
	//验证token，并获取用户名
	username, _, bfind := user.GetUserFromToken(req.Access_token)
	if !bfind {
		w.WriteJson(message.GetErrorMsg(message.TokenFailure))
		return
	}
	u, bb := user.GetUserDetail(username)
	if !bb {
		w.WriteJson(message.GetErrorMsg(message.UserNotExisted))
		return
	}
	//权限检验
	b := auth.CheckRoleAuth(u.Business_role, auth_const.M_10, auth_const.L_A, auth_const.L_B, auth_const.L_C)
	if !b {
		w.WriteJson(message.GetErrorMsg(message.UserMenuNotExisted))
		return
	}

	var db mysqldb.MySqlDB
	defer db.OnDestoryDB()
	orm := db.OnGetDBOrm(config.GetDbUrl())

	var tmp []Kv_tbl
	var result []Kv_view
	orm.Find(&tmp)

	if len(tmp) > 0 {
		for _, v := range tmp {
			var t Kv_view
			t.Key_id = v.Key_id
			t.Name = v.Name
			t.Options = strings.Split(v.Options, common.SPLIT)
			result = append(result, t)
		}
	}
	msg := message.GetSuccessMsg(message.NormalMessageId)
	msg.Data = result
	w.WriteJson(msg)
}

//新增或更新数据字典
func Action(w rest.ResponseWriter, r *rest.Request) {
	var req ActionParam
	tools.GetRequestJsonObj(r, &req)

	//参数检测
	if !tools.CheckParam(req.Access_token, req.Key_id) || req.Action == 0 {
		w.WriteJson(message.GetErrorMsg(message.ParameterInvalid, req))
		return
	}
	//验证token，并获取用户名
	_, _, bfind := user.GetUserFromToken(req.Access_token)
	if !bfind {
		w.WriteJson(message.GetErrorMsg(message.TokenFailure))
		return
	}
	var db mysqldb.MySqlDB
	defer db.OnDestoryDB()
	orm := db.OnGetDBOrm(config.GetDbUrl())

	var kv, tmp Kv_tbl
	if req.Action == 1 { //新增
		orm.Where("key_id = ?", req.Key_id).Or("name = ?", req.Name).Find(&tmp)
		if len(tmp.Key_id) > 0 {
			w.WriteJson(message.GetErrorMsg(message.ExistedError))
			return
		}
	} else if req.Action == 2 { //修改
		orm.Where("key_id = ?", req.Key_id).Find(&tmp)
		if len(tmp.Key_id) == 0 {
			w.WriteJson(message.GetErrorMsg(message.NotFindError))
			return
		}
	} else {
		w.WriteJson(message.GetErrorMsg(message.ParameterInvalid, req))
		return
	}
	kv.Name = req.Name
	if len(req.Options) > 0 {
		kv.Options = fmt.Sprintf("%s", req.Options[0])
		for i := 1; i < len(req.Options); i++ {
			kv.Options += common.SPLIT + fmt.Sprintf("%s", req.Options[i])
		}
	}
	// if len(req.Key) == 0 { //新增
	// 	kv.Key = tools.GetRandomString(3)
	// } else {
	// 	kv.Key = req.Key //编辑
	// }
	kv.Key_id = req.Key_id
	err := orm.Save(&kv).Error
	if err != nil {
		w.WriteJson(message.GetErrorMsg(message.UnknownError))
		return
	}
	msg := message.GetSuccessMsg()
	w.WriteJson(msg)
}

//获取全部字典关联
func GetRefAll(w rest.ResponseWriter, r *rest.Request) {
	var req GetAllParam
	tools.GetRequestJsonObj(r, &req)

	//参数检测
	if !tools.CheckParam(req.Access_token) {
		w.WriteJson(message.GetErrorMsg(message.ParameterInvalid, req))
		return
	}
	//验证token，并获取用户名
	username, _, bfind := user.GetUserFromToken(req.Access_token)
	if !bfind {
		w.WriteJson(message.GetErrorMsg(message.TokenFailure))
		return
	}
	u, bb := user.GetUserDetail(username)
	if !bb {
		w.WriteJson(message.GetErrorMsg(message.UserNotExisted))
		return
	}
	//权限检验
	b := auth.CheckRoleAuth(u.Business_role, auth_const.M_10, auth_const.L_A, auth_const.L_B, auth_const.L_C)
	if !b {
		w.WriteJson(message.GetErrorMsg(message.UserMenuNotExisted))
		return
	}
	var db mysqldb.MySqlDB
	defer db.OnDestoryDB()
	orm := db.OnGetDBOrm(config.GetDbUrl())

	//查找module
	var m []Module
	sql := orm.Table("kv_ref_tbl").Group("module")
	if len(req.Module) > 0 {
		sql = sql.Where("module = ?", req.Module)
	}
	sql.Find(&m)

	var result []Kv_ref_info
	if len(m) > 0 {
		for _, v := range m {
			var t Kv_ref_info
			t.Module = v.Module
			var tmp []*Kv_ref_view
			sql := orm.Table("kv_ref_tbl as r").Select("r.*,k.*").Joins("left join kv_tbl as k on r.value = k.key_id").
				Where("r.module = ?", v.Module)
			if len(req.Field) > 0 {
				sql = sql.Where("r.field = ?", req.Field)
			}
			sql.Find(&tmp)
			if len(tmp) > 0 {
				for _, v := range tmp {
					v.Options_s = strings.Split(v.Options, common.SPLIT)
				}
			}
			t.Field_list = tmp
			result = append(result, t)
		}
	}
	msg := message.GetSuccessMsg(message.NormalMessageId)
	msg.Data = result
	w.WriteJson(msg)
}

//修改字典关联
func UpdateRef(w rest.ResponseWriter, r *rest.Request) {
	var req UpdateRefParam
	tools.GetRequestJsonObj(r, &req)

	//参数检测
	if !tools.CheckParam(req.Access_token, req.Module, req.Field, req.Type) {
		w.WriteJson(message.GetErrorMsg(message.ParameterInvalid, req))
		return
	}
	//验证token，并获取用户名
	username, _, bfind := user.GetUserFromToken(req.Access_token)
	if !bfind {
		w.WriteJson(message.GetErrorMsg(message.TokenFailure))
		return
	}
	u, bb := user.GetUserDetail(username)
	if !bb {
		w.WriteJson(message.GetErrorMsg(message.UserNotExisted))
		return
	}
	//权限检验
	b := auth.CheckRoleAuth(u.Business_role, auth_const.M_10, auth_const.L_A, auth_const.L_C)
	if !b {
		w.WriteJson(message.GetErrorMsg(message.UserMenuNotExisted))
		return
	}
	var db mysqldb.MySqlDB
	defer db.OnDestoryDB()
	orm := db.OnGetDBOrm(config.GetDbUrl())

	var ref Kv_ref_tbl
	orm.Where("module = ? and field = ?", req.Module, req.Field).Find(&ref)
	if ref.Id == 0 {
		w.WriteJson(message.GetErrorMsg(message.NotFindError, "字段不存在"))
		return
	}
	//判断是否存在
	if req.Type == common.KV {
		var tmp Kv_tbl
		orm.Where("key_id = ?", req.Value).Find(&tmp)
		if len(tmp.Key_id) == 0 {
			w.WriteJson(message.GetErrorMsg(message.NotFindError, "数据字典不存在"))
			return
		}
	}
	mp := map[string]interface{}{"type": req.Type, "value": req.Value}
	err := orm.Table("kv_ref_tbl").Where("module = ? and field = ?", req.Module, req.Field).
		Updates(mp).Error
	if err != nil {
		w.WriteJson(message.GetErrorMsg(message.UnknownError))
		return
	}
	w.WriteJson(message.GetSuccessMsg(message.NormalMessageId))
}

//删除数据字典
func Delete(w rest.ResponseWriter, r *rest.Request) {
	var req ActionParam
	tools.GetRequestJsonObj(r, &req)

	//参数检测
	if !tools.CheckParam(req.Access_token, req.Key_id) {
		w.WriteJson(message.GetErrorMsg(message.ParameterInvalid, req))
		return
	}
	//验证token，并获取用户名
	username, _, bfind := user.GetUserFromToken(req.Access_token)
	if !bfind {
		w.WriteJson(message.GetErrorMsg(message.TokenFailure))
		return
	}
	u, bb := user.GetUserDetail(username)
	if !bb {
		w.WriteJson(message.GetErrorMsg(message.UserNotExisted))
		return
	}
	//权限检验
	b := auth.CheckRoleAuth(u.Business_role, auth_const.M_10, auth_const.L_C)
	if !b {
		w.WriteJson(message.GetErrorMsg(message.UserMenuNotExisted))
		return
	}
	var db mysqldb.MySqlDB
	defer db.OnDestoryDB()
	orm := db.OnGetDBOrm(config.GetDbUrl())
	//判断能否删除
	var ref []Kv_ref_tbl
	orm.Where("type = ? and value = ?", common.KV, req.Key_id).Find(&ref)
	if len(ref) > 0 {
		w.WriteJson(message.GetErrorMsg(message.InValidOp, "存在字段关联"))
		return
	}
	err := orm.Delete(Kv_tbl{}, "key_id = ?", req.Key_id).Error
	if err != nil {
		w.WriteJson(message.GetErrorMsg(message.UnknownError))
		return
	}
	w.WriteJson(message.GetSuccessMsg(message.NormalMessageId))
}
